import lib from '@/lib';
import Vue from 'vue';
import Vuex from 'vuex';
import img from '../lib/img';
import TodoManageModal from '@/service/TodoManageModal';
import MailListModule from '@/components/MailListModule/modal';
import CalendarViewModule from '@/components/CalendarViewModule/modal';
import BatchImportModule from '@/components/BatchImportModule/modal';

Vue.use(Vuex);

interface IActionFirPayload extends Modal.ActionsFirPayload {
  state: Modal.Store.State;
}

const storeOp: Modal.Store.Instance = {
  state: {
    name: '待办管理器',
    theme: 'primary',
    copyRight: '©2020 TodoManage wws1993<15696141050@163.com>',
    listGroup: [
      {label: '还没做', list: [], currentWeight: 0, icon: img.todo},
      {label: '正在搞', list: [], currentWeight: 0, icon: img.doing},
      {label: '做完啦', list: [], currentWeight: 0, icon: img.done},
    ],
    manage: {
      visible: false,
      mode: '新增',
      form: {
        subject: '',
        weight: 3,
        content: '',
        startTime: '',
        endTime: '',
        person: [],
      },
    },
    allProjectSubjects: [],
  },
  mutations: {
  },
  actions: {
    /** 打开弹窗，进行编辑或新增操作 */
    openManage({state}: IActionFirPayload, payload: 'add' | Manage.Instance) {
      if (payload === 'add') {
        const t: Date | undefined = new Date();
        const d: Date | undefined = new Date(new Date().setDate(t.getDate() + 1));

        state.manage.form = {
          subject: '',
          weight: 3,
          content: '',
          startTime: t.format(),
          endTime: d.format(),
          person: [],
        };

        state.manage.mode = '新增';
      } else {
        state.manage.form = {...payload};
        state.manage.mode = payload.subject;
      }

      state.manage.visible = true;
      setTimeout(() => {
        const node = document.getElementById('autoFocusForEditTodoManage');
        node?.focus();
      }, 0);
    },
    /** 关闭弹窗 */
    closeManage({state}: IActionFirPayload) { state.manage.visible = false; },
    /** 保存 */
    saveManage({state, dispatch}: IActionFirPayload, payload: Manage.Instance) {
      if (!payload.hasOwnProperty('startTime')) {
        payload = state.manage.form;
      }

      dispatch('verifyManage', payload)
        .then(() => TodoManageModal.save(payload))
        .then((res: any) => {
          lib.notify('保存成功', '', 'success');
          state.manage.visible = false;
          dispatch('queryManage');
        }).catch((err: any) => {
          lib.notify('保存失败', err, 'error');
          console.log(2, err);
        });
    },
    /** 校验表单 */
    verifyManage({state}: IActionFirPayload, payload: Manage.Instance) {
      return new Promise((resolve, reject) => {
        if (!payload.subject) {
          return lib.notify('保存失败', '你忘了写主题啦！', 'warning');
        } else {
          resolve();
        }
      });
    },
    /** 查询待办（全量） */
    queryManage({state}: IActionFirPayload) {
      state.listGroup.map(k => k.list = []);                      // 重置每个待办list

      TodoManageModal.request().then(res => {                     // 以待办状态 分类存放待办
        if (res) {
          const clone = [...res];
          state.allProjectSubjects = clone.map(k => k && {id: k.id, name: k.subject}) as any;

          res.map(item => {
            state.listGroup[item.todoStatus as number || 0].list.push(item);
          });
        }
      });
    },
    /** 设置某列表权重，刷新渲染 */
    setListWeight({state}: IActionFirPayload, {idx, weight}: {idx: number, weight: 0|1|2|-1}) {
      state.listGroup[idx].currentWeight = weight;
    },
    /** 更新待办 */
    updateManage({state, dispatch}: IActionFirPayload, payload: Manage.Instance) {
      if (!payload.hasOwnProperty('startTime')) {
        payload = state.manage.form;
      }

      payload.isBatch = undefined;
      TodoManageModal.save(payload).then(() => {
        dispatch('queryManage').then(() => {
          // 若日历视图打开 则重新渲染
          if (state.CalendarViewModule.visible) {
            dispatch('CalendarViewModule/render');
          }
        });
      }).catch(err => {
        lib.notify('修改待办失败', '', 'error');
      });
    },
    deleteManage({state, dispatch}: IActionFirPayload, payload: number|number[]) {
      TodoManageModal.del(payload).then(() => {
        lib.notify('删除成功', '', 'success');
      }).catch(() => {
        lib.notify('删除失败', '', 'error');
      }).finally(() => {
        dispatch('queryManage');
      });
    },
    /** 根据条件检出待办 */
    checkoutTodoManage({state}: IActionFirPayload, filterKeys: API.params.TodoManageModal.Query) {
      return TodoManageModal.request(filterKeys);
    },
  },
  modules: {
    CalendarViewModule,
    MailListModule,
    BatchImportModule,
  },
};

export default new Vuex.Store(storeOp);
